Python provides several built-in data structures to store collections of data. The most commonly used are Lists, Tuples, and Sets. Each has unique features and use cases.
1. Lists in Python
A list is an ordered, mutable (changeable) collection of items. Lists can hold elements of different data types.
Creating a List
fruits = ["apple", "banana", "cherry"]
print(fruits) # ['apple', 'banana', 'cherry']
Accessing Elements
print(fruits[0]) # apple
print(fruits[-1]) # cherry
Modifying Lists
fruits[1] = "mango"
print(fruits) # ['apple', 'mango', 'cherry']
List Methods
* `append()` – Add element at the end
* `insert()` – Insert at specific index
* `remove()` – Remove by value
* `pop()` – Remove by index
* `sort()` – Sort the list
* `reverse()` – Reverse the list
Example:
numbers = [3, 1, 4, 2]
numbers.sort()
print(numbers) # [1, 2, 3, 4]
2. Tuples in Python
A tuple is an ordered, immutable collection of elements. Once created, you cannot modify a tuple.
Creating a Tuple
dimensions = (1920, 1080)
print(dimensions) # (1920, 1080)
Accessing Elements
print(dimensions[0]) # 1920
Why Use Tuples?
* They are faster than lists
* Useful for fixed data (e.g., coordinates)
Tuple Methods
* `count()` – Count occurrences
* `index()` – Find index of an element
Example:
colors = ("red", "blue", "red")
print(colors.count("red")) # 2
3. Sets in Python
A set is an unordered collection of unique elements.
* No duplicate values
* No indexing or slicing
Creating a Set
colors = {"red", "green", "blue"}
print(colors) # {'blue', 'green', 'red'}
Adding and Removing Elements
colors.add("yellow")
colors.remove("red")
print(colors) # {'blue', 'green', 'yellow'}
Set Operations
* `union()` → Combines elements from both sets
* `intersection()` → Common elements
* `difference()` → Elements present in one set but not the other
Example:
a = {1, 2, 3}
b = {3, 4, 5}
print(a.union(b)) # {1, 2, 3, 4, 5}
print(a.intersection(b)) # {3}
Summary
* Lists – Ordered, mutable, allows duplicates
* Tuples – Ordered, immutable, allows duplicates
* Sets – Unordered, mutable, no duplicates